//
//  SystemManager.m
//  newBooks
//
//  Created by 张 on 2019/1/11.
//  Copyright © 2019年 pro2. All rights reserved.
//

#import "SystemManager.h"


@implementation SystemManager

//DEF_SINGLETON(SystemManager)

+(void)load{
    [self shareManager];
}

+(SystemManager *)shareManager{
    static SystemManager *instance = nil;
    static dispatch_once_t oneToken;
    dispatch_once(&oneToken,^{
        instance = [[SystemManager alloc] init];
    });
    return instance;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        //在UIApplicationDidFinishLaunching时初始化开屏广告,做到对业务层无干扰,当然你也可以直接在AppDelegate didFinishLaunchingWithOptions方法中初始化
        [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidFinishLaunchingNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
            //初始化开屏广告
            [self configSystem];
        }];
    }
    return self;
}

- (void)configSystem
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    //配置网络header
    [BANetManager sharedBANetManager].httpHeaderFieldDictionary = @{@"token":[UserDefaults getAccessToken] ? [UserDefaults getAccessToken] : @"",@"system":@"1",@"version": [infoDictionary objectForKey:@"CFBundleShortVersionString"]};
    weakify(self);
    if (StringIsEmpty([[NSUserDefaults standardUserDefaults] objectForKey:@"ADIMGURL"]) == NO) {
        //广告存在 - 展示广告
        [self showADViewWithUrl:[[NSUserDefaults standardUserDefaults] objectForKey:@"ADTURNURL"]];
    }
    [self checkAppUpdateSuccess:^(NSDictionary * value){
        strongify(self);
        if (value[@"startup"]) {
            NSString * imgStr = value[@"startup"][@"image"];
            NSString * url = value[@"startup"][@"url"];
            if (StringIsEmpty(url) == NO) {
                [[NSUserDefaults standardUserDefaults] setObject:url forKey:@"ADTURNURL"];
            }else{
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"ADTURNURL"];
            }
            [[NSUserDefaults standardUserDefaults] setObject:imgStr forKey:@"ADIMGURL"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }else{
            [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"ADIMGURL"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        if ([value[@"version_info"][@"is_update"] integerValue] == 1) {
            [self showUpdateAlertWithUrl:@"https://itunes.apple.com/cn/app/id1450344304?mt=8" isforce:value[@"version_info"][@"is_force"]];
        }
    } failed:^(NSString *error) {
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"ADIMGURL"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }];
}

- (void)showUpdateAlertWithUrl:(NSString *)url isforce:(id)isforce
{
    //isforce 是否强制更新：1->不强制，2=>强制
    UIWindow *alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    alertWindow.rootViewController = [[UIViewController alloc] init];
    alertWindow.windowLevel = UIWindowLevelAlert + 1;
    [alertWindow makeKeyAndVisible];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"更新提示" message:@"发现新版本。为保证各项功能正常使用，请您尽快更新。" preferredStyle:UIAlertControllerStyleAlert];
    //显示弹出框
    [alertWindow.rootViewController presentViewController:alert animated:YES completion:nil];
    if ([isforce integerValue] == 1) {
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
    }
    [alert addAction:[UIAlertAction actionWithTitle:@"现在更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    }]];
}

- (void)showADViewWithUrl:(NSString *)turnUrl;
{
    [XHLaunchAd setLaunchSourceType:SourceTypeLaunchImage];
    //配置广告数据
    XHLaunchImageAdConfiguration *imageAdconfiguration = [XHLaunchImageAdConfiguration new];
    imageAdconfiguration.duration = 3;
    imageAdconfiguration.imageOption = XHLaunchAdImageRefreshCached;
    imageAdconfiguration.contentMode = UIViewContentModeScaleToFill;
    imageAdconfiguration.showFinishAnimate =ShowFinishAnimateFadein;
    //跳过按钮类型
    imageAdconfiguration.skipButtonType = SkipTypeTimeText;
    //后台返回时,是否显示广告
    imageAdconfiguration.showEnterForeground = NO;
    imageAdconfiguration.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);

    //广告图片URLString/或本地图片名(.jpg/.gif请带上后缀)
    imageAdconfiguration.imageNameOrURLString = [[NSUserDefaults standardUserDefaults] objectForKey:@"ADIMGURL"];
    //广告点击打开页面参数(openModel可为NSString,模型,字典等任意类型)
    imageAdconfiguration.openModel = StringIsEmpty(turnUrl) ? nil : turnUrl;
    //显示图片开屏广告
    [XHLaunchAd imageAdWithImageAdConfiguration:imageAdconfiguration delegate:self];
}

/**
 广告点击事件代理方法
 */
- (void)xhLaunchAd:(XHLaunchAd *)launchAd clickAndOpenModel:(id)openModel clickPoint:(CGPoint)clickPoint{
    NSLog(@"广告点击事件");
    /** openModel即配置广告数据设置的点击广告时打开页面参数(configuration.openModel) */
    if(openModel==nil) return;
    NSString *urlString = (NSString *)openModel;
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
}

+ (NSString *)getDateWith:(NSString *)pan{
    NSDate *date = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = [NSString stringWithFormat:@"MM dd%@yyyy",pan];
    NSString *string = [fmt stringFromDate:date];
    string = [string stringByReplacingCharactersInRange:NSMakeRange(0, 2) withString:[SystemManager monthEnWith:[string substringWithRange:NSMakeRange(0, 2)]]];
    return string;
}

+ (NSString *)monthEnWith:(NSString *)month{
    if ([month isEqualToString:@"01"]) {
        return @"January";
    }
    else if ([month isEqualToString:@"02"]){
        return @"February";
    }
    else if ([month isEqualToString:@"03"]){
        return @"March";
    }
    else if ([month isEqualToString:@"04"]){
        return @"April";
    }
    else if ([month isEqualToString:@"05"]){
        return @"May";
    }
    else if ([month isEqualToString:@"06"]){
        return @"June";
    }
    else if ([month isEqualToString:@"07"]){
        return @"July";
    }
    else if ([month isEqualToString:@"08"]){
        return @"August";
    }
    else if ([month isEqualToString:@"09"]){
        return @"September";
    }
    else if ([month isEqualToString:@"10"]){
        return @"October";
    }
    else if ([month isEqualToString:@"11"]){
        return @"November";
    }
    else if ([month isEqualToString:@"12"]){
        return @"December";
    }
    else{
        return @"";
    }
}

- (void)getLocalWeatherwithBlock:(void(^)(NSString * weatherStr,NSString * weatherImg))successBlock
{
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//    });
    self.localBlock = successBlock;
    // 判断定位操作是否被允许
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init] ;
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8) {
            //由于IOS8中定位的授权机制改变 需要进行手动授权
            [self.locationManager requestWhenInUseAuthorization];
        }
        [self.locationManager startUpdatingLocation];// 开始定位
    }else
    {
        [QMUITips showWithText:@"定位暂未开启"];
    }
}

- (void)getWeatherWithCity:(NSString *)city
{
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = @"https://www.tianqiapi.com/api/";
    entity.needCache = NO;
    entity.parameters = @{@"version":@"v1",@"city":city};
    [BANetManager ba_request_GETWithEntity:entity successBlock:^(id response) {
        NSString * img = @"太阳";
        NSArray * arr = response[@"data"];
        NSString * weather = arr.firstObject[@"wea"];
        if ([weather containsString:@"阴"]) {
            img = @"阴";
        }else if ([weather containsString:@"雪"])
        {
            img = @"雪花";
        }else if ([weather containsString:@"雨"])
        {
            img = @"雨";
        }
        self.localBlock(weather, img);
    } failureBlock:^(NSError *error) {
    } progressBlock:nil];
}

#pragma mark - corelocationdelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLGeocoder *reverseGeocoder=[[CLGeocoder alloc]  init];
    [reverseGeocoder reverseGeocodeLocation:[locations firstObject] completionHandler:^(NSArray *array, NSError *error)
     {
         CLPlacemark *placeMark = [array lastObject];
         if (placeMark != nil)
         {
             NSString *CityName = [placeMark.addressDictionary objectForKey:@"City"];
             NSLog(@"城市名:%@",CityName);
             if ([CityName containsString:@"市"]) {
                 CityName = [CityName stringByReplacingOccurrencesOfString:@"市" withString:@""];
             }else if ([CityName containsString:@"区"]){
                 CityName = [CityName stringByReplacingOccurrencesOfString:@"区" withString:@""];
             }
             [self getWeatherWithCity:CityName];
         }
     }];
    //如果不需要实时定位，使用完即使关闭定位服务
    [self.locationManager stopUpdatingLocation];
}
@end
